# coding:utf-8
import configparser
import os

import sys
from selenium import webdriver
import time
import requests
import re


class Qzone:
    def __init__(self):
        self.url = 'https://qzone.qq.com/'
        self.desc_url = 'https://user.qzone.qq.com/516960831'
        self.filename = 'ext/E10_qzone_requests_selenium_cookies.html'
        self.driver = None

    def run(self):
        self.driver = webdriver.Chrome()
        self.driver.get(self.url)
        time.sleep(3)

        _el_iframe = self.driver.find_element_by_xpath('//*[@id="login_frame"]')
        self.driver.switch_to.frame(_el_iframe)
        _el = self.driver.find_element_by_xpath('//*[@id="switcher_plogin"]')
        _el.click()
        time.sleep(2)

        user_pswd_cfg = os.environ['user_pswd']
        cf = configparser.ConfigParser()
        cf.read(user_pswd_cfg)
        _user = cf.get('qq', 'qq_user')
        _pswd = cf.get('qq', 'qq_pswd')
        _el_user = self.driver.find_element_by_xpath('//*[@id="u"]')
        _el_user.send_keys(_user)
        _el_pwd = self.driver.find_element_by_xpath('//*[@id="p"]')
        _el_pwd.send_keys(_pswd)

        _el_sub = self.driver.find_element_by_xpath('//*[@id="login_button"]')
        _el_sub.click()
        time.sleep(2)
        _el_sub.click()

        _path = os.path.join(os.path.abspath('.'), '../')
        sys.path.append(_path)
        _ei = __import__('Utils.C002_extract_info', fromlist=['C002_extract_info'])
        _ua_file = {'pc': '{0}Utils/{1}'.format(_path, _ei.ExtractInfo.ua_file['pc'])}
        _user_agent = _ei.ExtractInfo.get_useragent(file=_ua_file)
        _cookies_dict = {}
        list_cookies = self.driver.get_cookies()
        for infos in list_cookies:
            _cookies_dict[infos['name']] = infos['value']
        _response = requests.get(self.desc_url, headers=_user_agent, cookies=_cookies_dict, verify=False)
        print(_cookies_dict)
        print(_response.content.decode())
        if re.findall(r'浅唱流年', _response.content.decode()):
            with open(self.filename, mode='w', encoding='utf-8')as f:
                f.write(_response.content.decode())
        else:
            print('not found!')

    def __del__(self):
        self.driver.close()


def main():
    qz = Qzone()
    qz.run()


if __name__ == '__main__':
    main()
